/**
 * 文件名    ： DruidConfig.java
 * 版权       : XX科技有限公司。
 * 描述       : <描述>
 * 修改时间：2017年5月30日
 * 修改内容：<修改内容>
 */
package com.example.demo.application.common.config;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.example.demo.application.common.MyConstants;
import com.example.demo.application.common.encrypt.AES;
import com.example.demo.application.common.encrypt.EncryptConfig;

//使用 Druid 链接池 时 ， 放开下面的注释
@Configuration
public class DruidConfig {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${spring.datasource.url}")
	private String dbUrl;
	
	@Value("${spring.datasource.username}")
	private String username;
	
	@Value("${spring.datasource.password.prefix}")
	private String passwordkey1;
	
	@Value("${spring.datasource.password.suffix}")
	private String passwordkey2;
	
	@Value("${spring.datasource.driver-class-name}")
	private String driverClassName;
	
	@Value("${spring.datasource.initialSize}")
	private int initialSize;
	
	@Value("${spring.datasource.minIdle}")
	private int minIdle;
	
	@Value("${spring.datasource.maxActive}")
	private int maxActive;
	
	@Value("${spring.datasource.maxWait}")
	private int maxWait;
	
	@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;
	
	@Value("${spring.datasource.minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;
	
	@Value("${spring.datasource.validationQuery}")
	private String validationQuery;
	
	@Value("${spring.datasource.testWhileIdle}")
	private boolean testWhileIdle;
	
	@Value("${spring.datasource.testOnBorrow}")
	private boolean testOnBorrow;
	
	@Value("${spring.datasource.testOnReturn}")
	private boolean testOnReturn;
	
	@Value("${spring.datasource.poolPreparedStatements}")
	private boolean poolPreparedStatements;
	
	@Value("${spring.datasource.filters}")
	private String filters;
	
	
	@Value("${root.key1.config.file.path}")
	private String rootKey1FilePath;
	
	@Value("${root.key2.config.file.path}")
	private String rootKey2FilePath;
	
	@Value("${redis.config.file.path}")
	private String redisConfigFilePath;
	
	@Bean
	public ServletRegistrationBean druidServlet() {
		ServletRegistrationBean reg = new ServletRegistrationBean();
		reg.setServlet(new StatViewServlet());
		reg.addUrlMappings("/druid/*");
		reg.addInitParameter("loginUsername", "druidclw");
		reg.addInitParameter("loginPassword", "7930c834b14c_6");
		//是否允许重置
		reg.addInitParameter("resetEnable","false");
		//是否开启session监控
		reg.addInitParameter("sessionStatEnable","false");
		reg.addInitParameter("sessionStatMaxCount","1");
		return reg;
	}
	
	@Bean
	public FilterRegistrationBean filterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new WebStatFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		filterRegistrationBean.addInitParameter("profileEnable", "true");
		filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
		filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
		return filterRegistrationBean;
	}
	
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	@Primary
	public DataSource druidDataSource(){ 
		DruidDataSource datasource = new DruidDataSource(); 
		if (StringUtils.isBlank(EncryptConfig.rootKey)) {
			this.init();
		}
		if(StringUtils.isBlank(EncryptConfig.redisConfigFilePath)) {
			EncryptConfig.redisConfigFilePath=redisConfigFilePath;
		}
		
		datasource.setUrl(this.dbUrl); 
		datasource.setUsername(username); 
		String mysqlKey1;
		try {
			mysqlKey1 = AES.decrypt(passwordkey1, EncryptConfig.rootKey);
			String mysqlKey2 = AES.decrypt(passwordkey2, EncryptConfig.rootKey);
			//			47c95b226ebf4287893007c834b194c6
			String pass = mysqlKey1+mysqlKey2;
			datasource.setPassword(pass); 
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		datasource.setDriverClassName(driverClassName); 
		datasource.setInitialSize(initialSize); 
		datasource.setMinIdle(minIdle); 
		datasource.setMaxActive(maxActive); 
		datasource.setMaxWait(maxWait); 
		datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 
		datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 
		datasource.setValidationQuery(validationQuery); 
		datasource.setTestWhileIdle(testWhileIdle); 
		datasource.setTestOnBorrow(testOnBorrow); 
		datasource.setTestOnReturn(testOnReturn); 
		datasource.setPoolPreparedStatements(poolPreparedStatements); 
		try { 
		datasource.setFilters(filters); 
		} catch (SQLException e) { 
		logger.error("druid configuration initialization filter", e); 
		} 
		return datasource; 
	}
	
	
	
	/**
	 * <功能> 初始化 <详细描述> 配置 初始化
	 * 
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private synchronized void init() {
		String key1 = "";
		String key2 = "";
		ResourceBundle bundle = null;
		try {
			BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(rootKey1FilePath));
			bundle = new PropertyResourceBundle(inputStream);
			key1 = bundle.getString("root_key_1").trim();
			inputStream.close();
		} catch (IOException e1) {
			logger.error(" RootKey1File : ", e1);
		}
		if (StringUtils.isBlank(key1)) {
			logger.error("[RootKey1File] is not found!");
			throw new IllegalArgumentException("[RootKey1File] is not found!");
		}

		try {
			BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(rootKey2FilePath));
			bundle = new PropertyResourceBundle(inputStream);
			key2 = bundle.getString("root_key_last").trim();
			inputStream.close();
		} catch (IOException e1) {
			logger.error(" RootKey2File init : ", e1);
		}
		if (StringUtils.isBlank(key2)) {
			logger.error("[RootKey2File] is not found!");
			throw new IllegalArgumentException("[RootKey2File] is not found!");
		}
		bundle = null;

		// 解密
		String deString;
		try {
			deString = AES.decrypt(key1, MyConstants.ROOT_FATHER_KEY);
			String deString_last = AES.decrypt(key2, MyConstants.ROOT_FATHER_KEY);
			EncryptConfig.rootKey = deString + deString_last;
		} catch (Exception e) {
			logger.error("rootKey AES.decrypt ERR !");
			throw new IllegalArgumentException("rootKey AES.decrypt ERR !");
		}
	}
}